package com.spring.springcloud.Elasticsearch;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class C_ES的批量操作 {
    public static void main(String[] args) throws IOException {

        //在 Elasticsearch  8.x的版本已过期
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
        );
        String sy = "user";//对此索引操作

//        批量添加(esClient, sy);
//        批量删除(esClient, sy);

        esClient.close();//关闭客户端
    }

    private static void 批量删除(RestHighLevelClient esClient, String sy) throws IOException {
        //批量删除
        BulkRequest rq = new BulkRequest();
        DeleteRequest user1 = new DeleteRequest().index(sy).id("1004");
        rq.add(user1);//添加
        DeleteRequest user2 = new DeleteRequest().index(sy).id("1005");
        rq.add(user2);//添加
        //执行
        BulkResponse bulkResponse = esClient.bulk(rq, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.getTook());
        System.out.println(bulkResponse.getItems());
    }

    private static void 批量添加(RestHighLevelClient esClient, String sy) throws IOException {
        BulkRequest rq = new BulkRequest();

        IndexRequest user1 = new IndexRequest().index(sy).id("1004");
        user1.source(XContentType.JSON,"name","张三4");
        rq.add(user1);//添加
        IndexRequest user2 = new IndexRequest().index(sy).id("1005");
        user2.source(XContentType.JSON,"name","张三5");
        rq.add(user2);//添加

        //执行
        BulkResponse bulkResponse = esClient.bulk(rq, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.getTook());
        System.out.println(bulkResponse.getItems());
    }

}
